package com.bonc.ioc.util;

import com.bonc.ioc.validation.OSinfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;


@Component
public class BackUpDataBaseManager {
    private static final Logger log = LoggerFactory.getLogger(BackUpDataBaseManager.class);
    @Value("${spring.datasource.driver-class-name}")
    private String driverClassName;
    @Value("${spring.datasource.url}")
    private String url;
    @Value("${spring.datasource.username}")
    private String userName;
    @Value("${spring.datasource.password}")
    private String password;


//    @Value("${cmd}")
//    private String cmd;

    //@Value("${sqlbackup.path}")
    //private String sqlPath = System.getProperty("user.dir") + "\\";
//    @Value("${sqlbackup.staticPath}")
//    private String sqlStaticPath;

    /**
     * 获取数据库名
     */
    public String getDataBaseName() {
        return url.substring(url.indexOf("3306"), url.indexOf("?")).replaceAll("/", "").replaceAll("3306", "");
    }

    /**
     * 获取主机地址
     */
    private String getHost() {
        return url.substring(url.indexOf("mysql"), url.indexOf("3306")).replace(":", "").replace("//", "").replace("mysql", "");
    }

    /**
     *
     * @param sqlPath  导出的文件路径
     * @param fileName 导出的文件名称
     */
    public void exportSql(String sqlPath, String fileName) {
        // 指定导出的 sql 存放的文件夹
        File saveFile = new File(sqlPath);
        if (!saveFile.exists()) {
            saveFile.mkdirs();
        }

        String host = getHost();
        String dataBaseName = getDataBaseName();

        try {
            if (OSinfo.isLinux()) { //linux系统
                StringBuffer command = new StringBuffer();
                command.append("mysqldump -u").append(userName).append(" -p").append(password)//密码是用的小p，而端口是用的大P。
                        .append(" -h").append(host).append(" --opt ").append(dataBaseName).append(" ")
                        .append("standard").append(" ").append("standard_basic_data standard_basic_data_option standard_detail")
                        .append(" > ").append(sqlPath + fileName);
                String[] cmd = {"/bin/sh", "-c", command.toString()};//拼接指令
                System.out.println(Arrays.toString(cmd));

                Process exec = Runtime.getRuntime().exec(cmd);
                if (exec.waitFor() == 0) {
                    log.info("数据库备份成功，保存路径：" + sqlPath);
                } else {
                    System.out.println("process.waitFor()=" + exec.waitFor());
                }
            } else if (OSinfo.isWindows()) { //windows系统
                StringBuffer command = new StringBuffer();
                command.append("cmd /c mysqldump -u").append(userName).append(" -p").append(password)
                        .append(" -h").append(host).append(" --opt ").append(dataBaseName).append(" ")
                        .append("standard").append(" ").append("standard_basic_data standard_basic_data_option standard_detail")
                        .append(" > ").append(sqlPath + fileName);//拼接指令

                System.out.println(command);

                Process exec = Runtime.getRuntime().exec(command.toString());
                if (exec.waitFor() == 0) {
                    log.info("数据库备份成功，保存路径：" + sqlPath);
                } else {
                    System.out.println("process.waitFor()=" + exec.waitFor());
                }

            }
        } catch (IOException e) {
            log.error("备份 数据库 出现 IO异常 ", e);
        } catch (InterruptedException e) {
            log.error("备份 数据库 出现 线程中断异常 ", e);
        } catch (Exception e) {
            log.error("备份 数据库 出现 其他异常 ", e);
        }
    }
}
